#! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on 2020/1/13 15:21 星期一

@author: jyz
"""

import time
import os

import requests

from config.config_setting import IP, ALGORITHM_PARAMS, DEVICE_ALGORITHM


# 得到人脸库数据，get请求，参数为空
def get_face_data():
    url = IP + '/fvs/api/alg/person/list'
    r = requests.get(url)
    request_content = eval(r.text)['data']
    person_name = [req['name'] for req in request_content]
    person_image = [req['imgList'] for req in request_content]
    return person_name, person_image


# 得到设备（摄像头）的rtsp地址，get请求，参数为空
def get_camera_rtsp_url():
    url = IP + '/fvs/api/alg/device/list'
    r = requests.get(url)
    request_content = eval(r.text)['data']['list']

    src_stream_urls = [req['srcStreamUrl'] for req in request_content]
    user_names = [req['username'] for req in request_content]
    passwords = [req['password'] for req in request_content]
    device_ids = [req['deviceId'] for req in request_content]

    camera_paths = {}
    # 得到访问摄像头的rtmp地址
    for srcStreamUrl, userName, password, deviceId in zip(src_stream_urls, user_names, passwords, device_ids):
        prefix_src_stream_url = srcStreamUrl.split('//')[0]
        back_src_stream_url = srcStreamUrl.split('//')[1]
        camera_paths[deviceId] = prefix_src_stream_url + '//' + userName + ':' + password + '@' + back_src_stream_url
    return camera_paths, device_ids


# 得到摄像头需要实现的算法
# 功能列表{安全帽：10，反光衣：20，越界：30，人员聚集：40，摔倒行为检测：50，人员离岗：60，人员徘徊：70，裸土覆盖：80，火焰检测：90}
def get_camera_functions():
    url = IP + '/fvs/api/alg/device/list'
    r = requests.get(url)
    if r.status_code == 200:
        # print('请求成功')
        pass
    else:
        print('请求失败，重新请求...')
        r = requests.get(url)
    request_content = eval(r.text)['data']['list']

    camera_functions, device_params = [], []
    for device_content in request_content:
        device_id = device_content['deviceId']
        if 'config' in device_content.keys():  # 判断每个设备是否携带了配置参数，若没有，则pass。
            device_config = device_content['config']
            for device_conf in device_config:
                if device_conf['state'] != 0:  # 判断每个设备配置的算法是否状态，如果不可用则pass。
                    try:  # 根据算法名称获取算法需要的参数名
                        device_param = ALGORITHM_PARAMS[device_conf['type']]
                    except:
                        device_param = ''
                    if device_param:
                        device_params = device_conf['rule']
                    if 'timeList' in device_conf.keys():
                        camera_function = DEVICE_ALGORITHM(device_id, device_conf['type'], device_conf['timeList'], device_params)
                    else:
                        camera_function = DEVICE_ALGORITHM(device_id, device_conf['type'], [], device_params)
                    device_params = []
                    camera_functions.append(camera_function)

    return camera_functions


# 得到设备（摄像头）的rtmp地址
def get_camera_rtmp_url():
    rtmp_urls = {}
    _, _, rtmp_push_url = get_save_path()
    _, device_ids = get_camera_rtsp_url()
    for device_id in device_ids:
        rtmp_urls[device_id] = os.path.join(rtmp_push_url, str(device_id))
    return rtmp_urls


# 得到人脸以及抓拍图片保存本地保存地址，get请求，参数为空
def get_save_path():
    url = IP + '/fvs/api/alg/config'
    r = requests.get(url)
    request_content = eval(r.text)['data']

    face_img_path = request_content['faceImgPath']
    result_img_path = request_content['resultImgHttp']
    rtmp_push_url = request_content['rtmpPushUrl']
    return face_img_path, result_img_path, rtmp_push_url


# 算法识别结果上传，post请求，参数为Content-Type,deviceId,type,time,files_path，值为multipart/form-data,设备号，
def upload_det_result(c_type, c_time, device_id, img_name, result_path):
    url = IP + '/fvs/api/alg/result'
    device_payload = dict(Content_Type='multipart/form-data', deviceId=device_id, type=c_type, time=c_time,
                          resultImgPathList=result_path + '/' + img_name + '.jpg')
    requests.post(url, data=device_payload)


if __name__ == '__main__':
    func = get_camera_functions()
    print(func)
